package token

import (
	"cftgo/cftf/boot/app"
	"cftgo/cftf/db"
	"cftgo/cftf/ginhelper"
	"login/internal/common/constant"
	"login/model"
	"login/service/jwt"

	"github.com/gin-gonic/gin"
)

type Token struct {
}

type reqBodyObj struct {
	RefreshToken string `json:"refresh_token"`
}

func (this *Token) RefreshToken(c *gin.Context) {
	reqObj := new(reqBodyObj)
	if err := c.ShouldBindJSON(reqObj); err != nil {
		ginhelper.RspErr(c, 1, "params format error")
		return
	}
	if claims, err := jwt.ValidateToken(reqObj.RefreshToken); err != nil {
		ginhelper.RspErr(c, 1, "params format error")
		return
	} else {
		accModel := new(model.Account)
		result := db.GetOrmDb(constant.ACCOUNT_DB).First(&accModel, map[string]interface{}{
			"aid": claims.Subject,
		})
		if result.Error != nil {
			ginhelper.RspErr(c, 500, "server internal error")
			return
		}
		rspObj := &struct {
			ginhelper.CommonRspHead
			AccessToken  string `json:"access_token"`
			RefreshToken string `json:"refresh_token"`
			ExpiresIn    int64  `json:"expires_in"`
			ServerTime   int64  `json:"server_time"`
			AID          string `json:"aid"`
		}{}
		if tokenString, expiresIn, err := jwt.GenerateToken(accModel.Aid.String(), accModel.CreatedAt); err == nil {
			rspObj.AccessToken = tokenString
			rspObj.RefreshToken = tokenString
			rspObj.ServerTime = app.GetRealSeconds()
			rspObj.ExpiresIn = expiresIn
			rspObj.AID = accModel.Aid.String()
			ginhelper.RspData(c, rspObj)
		} else {
			ginhelper.RspErr(c, 500, "server internal error")
		}
	}
}
